<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    title="物料选择"
    :destroy-on-close="true"
    draggable
    :align-center="true"
    style="max-width: 1000px; max-height: 900px"
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      label-width="90"
      style="width: 100%; height: 100%"
      :rules="rules"
    >
      <h4 class="mb-[10px] mt-[0px]">产出成品</h4>
      <div style="display: flex; margin-bottom: 10px">
        <el-button type="success" @click="addBomRow"
          ><i-ep-plus />新增行</el-button
        >
        <div style="display: flex; justify-content: start">
          <el-checkbox
            v-model="isBomUnified"
            @change="changeBomUnified"
            style="margin-left: 25px"
            >线边库统一设置</el-checkbox
          >
          <el-form-item
            label-width="1"
            prop="bomProduceStorageId"
            :rules="!isBomUnified ? {} : rules.produceStorageId"
          >
            <el-select
              v-model="formData.bomProduceStorageId"
              placeholder="请选择线边库位"
              clearable
              @change="changeBomProduceStorage"
              :disabled="!isBomUnified"
            >
              <el-option
                v-for="item in produceStorageList"
                :key="item.id"
                :label="item.produceStorageCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        :data="formData.listBomMat"
        highlight-current-row
        border
        :cell-style="{ 'text-align': 'center' }"
        style="height: 200px"
      >
        <el-table-column
          label="物料号"
          align="center"
          prop="materialCode"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item label-width="1" class="equip-form-item">
              {{ scope.row.materialCode }}
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="物料名称"
          align="center"
          prop="materialName"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item label-width="1" class="equip-form-item">
              {{ scope.row.materialName }}
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="基础产出数量"
          align="center"
          prop="materialQuantity"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item
              label-width="1"
              :prop="'listBomMat.' + scope.$index + '.materialQuantity'"
              :rules="rules.materialQuantity"
            >
              <el-input-number
                v-model="scope.row.materialQuantity"
                style="width: 100%"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="数量单位"
          align="center"
          prop="quantityUnit"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item label-width="1" class="equip-form-item">
              {{ useDictionary("MeasurementUnit", scope.row.quantityUnit) }}
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="线边库位"
          align="center"
          prop="produceStorageId"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item
              label-width="1"
              :prop="'listBomMat.' + scope.$index + '.produceStorageId'"
              :rules="isBomUnified ? {} : rules.produceStorageId"
            >
              <el-select
                v-model="scope.row.produceStorageId"
                placeholder="线边库位"
                clearable
                :disabled="isBomUnified"
                style="width: 100%"
                @change="changeOutPutProduceStorage(scope.$index,scope.row.produceStorageId)"
              >
                <el-option
                  v-for="item in produceStorageList"
                  :key="item.id"
                  :label="item.produceStorageCode"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          prop="action"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item label-width="1" class="equip-form-item">
              <el-button
                type="primary"
                size="small"
                link
                @click="removeBomRow(scope.row)"
              >
                删除
              </el-button>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>

      <h4 class="mb-[10px] mt-[20px]">使用原材料</h4>

      <div style="display: flex; margin-bottom: 10px">
        <el-button type="success" @click="addOriginalRow"
          ><i-ep-plus />新增行</el-button
        >
        <div style="display: flex; justify-content: start">
          <el-checkbox
            v-model="isOriginalUnified"
            @change="changeOriginalUnified"
            style="margin-left: 25px"
            >线边库统一设置</el-checkbox
          >
          <el-form-item
            label-width="1"
            prop="originalProduceStorageId"
            :rules="!isOriginalUnified ? {} : rules.produceStorageId"
          >
            <el-select
              v-model="formData.originalProduceStorageId"
              placeholder="请选择线边库位"
              clearable
              @change="changeOriginalProduceStorage"
              :disabled="!isOriginalUnified"
            >
              <el-option
                v-for="item in produceStorageList"
                :key="item.id"
                :label="item.produceStorageCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        :data="formData.listOriginalMat"
        highlight-current-row
        border
        :cell-style="{ 'text-align': 'center' }"
        style="height: 300px"
      >
        <el-table-column
          label="物料号"
          align="center"
          prop="materialCode"
          min-width="100"
        >
          <template #default="scope">
            <template v-if="scope.row.type === 'search'">
              <el-form-item label-width="1" class="equip-form-item">
                {{ scope.row.materialCode }}
              </el-form-item>
            </template>
            <template v-if="scope.row.type === 'select'">
              <el-form-item
                label-width="1"
                :prop="'listOriginalMat.' + scope.$index + '.materialId'"
                :rules="rules.materialId"
              >
                <el-select
                  v-model="scope.row.materialId"
                  placeholder="请选择物料号"
                  @change="changeOriginalMaterial($event, scope.row)"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-if="scope.row.material"
                    :key="scope.row.material.materialId"
                    :label="scope.row.material.materialCode"
                    :value="scope.row.material.materialId"
                  />
                  <el-option
                    v-for="item in selectMaterialList"
                    :key="item.materialId"
                    :label="item.materialCode"
                    :value="item.materialId"
                  />
                </el-select>
              </el-form-item>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          label="物料名称"
          align="center"
          prop="materialName"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item label-width="1" class="equip-form-item">
              {{ scope.row.materialName }}
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="消耗量"
          align="center"
          prop="materialQuantity"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item
              label-width="1"
              :prop="'listOriginalMat.' + scope.$index + '.materialQuantity'"
              :rules="rules.materialQuantity"
            >
              <el-input-number
                v-model="scope.row.materialQuantity"
                style="width: 100%"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="数量单位"
          align="center"
          prop="quantityUnit"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item label-width="1" class="equip-form-item">
              {{
                scope.row.quantityUnit
                  ? useDictionary("MeasurementUnit", scope.row.quantityUnit)
                  : ""
              }}
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="线边库位"
          align="center"
          prop="produceStorageId"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item
              label-width="1"
              :prop="'listOriginalMat.' + scope.$index + '.produceStorageId'"
              :rules="isOriginalUnified ? {} : rules.produceStorageId"
            >
              <el-select
                v-model="scope.row.produceStorageId"
                placeholder="线边库位"
                clearable
                :disabled="isOriginalUnified"
                style="width: 100%"
                @change="changeRawProduceStorage(scope.$index,scope.row.produceStorageId)"
              >
                <el-option
                  v-for="item in produceStorageList"
                  :key="item.id"
                  :label="item.produceStorageCode"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          prop="action"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item label-width="1" class="equip-form-item">
              <el-button
                type="primary"
                size="small"
                link
                @click="removeOriginalRow(scope.row)"
              >
                删除
              </el-button>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <day-plan-mesbomtree
    :visible="bomTreeDialog.visible"
    :title="bomTreeDialog.title"
    :data="bomTreeDialog.data"
    @change-visible="changeBomTree"
  />
</template>
<script setup lang="ts">
import useEvent from "@/utils/useEvent";
import { productionVersionHook } from "@/views/mes/mesdayplan/hook/productionVersionHook";
import request from "@/utils/request";
import { concat } from "lodash-es";
import { useDictionary } from "@/utils/useTable";

const { eventBusEmit, eventBusOn } = useEvent();
const { event, api, validateDecimal } = productionVersionHook();
defineOptions({
  name: "DAYPLANPRODUCTIONVERSIONMATDIALOG",
  inheritAttrs: false,
});
const visibleDialog = ref(false);

const rowData = ref(null);

const formRef = ref(null);

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
watch(
  () => props.data,
  async (row: any) => {
    rowData.value = row;
    await getProduceStorageList();
    if (row.listMat) {
      const data = JSON.parse(JSON.stringify(row.listMat)).reduce(
        (acc, item) => {
          const key = item.materialRole;
          if (!acc[key]) {
            acc[key] = [];
          }
          acc[key].push(item);
          return acc;
        },
        {}
      );
      formData.listBomMat = data[1] ?? [];
      formData.listOriginalMat = data[0] ?? [];
      await buildTable(formData.listBomMat, false);
      reBuildSelectMaterialList();
    } else {
      formData.listBomMat = [];
      formData.listOriginalMat = [];
    }
  }
);
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

const isBomUnified = ref(false);
// const addBomRow = () => {
//   eventBusEmit(event.bomTree, formData.listBomMat);
// };

const removeBomRow = (row) => {
  const indexOf = formData.listBomMat.indexOf(row);
  formData.listBomMat.splice(indexOf, 1);
  buildTable(JSON.parse(JSON.stringify(formData.listBomMat)));
  formRef.value.validate();
};

const changeBomUnified = () => {
  if (isBomUnified.value) {
    formData.listBomMat.forEach((item) => {
      item.produceStorageId = formData.bomProduceStorageId;
    });
  }
  formRef.value.validate();
};
const changeBomProduceStorage = () => {
  formData.listBomMat.forEach((item,index) => {
    changeOutPutProduceStorage(index,formData.bomProduceStorageId)
  });
};
const changeOutPutProduceStorage = (index: number, id: string) => {
  produceStorageList.value.forEach((item: any) => {
    if (!id) {
      formData.listBomMat[index].produceStorageId = "";
      formData.listBomMat[index].produceStorageCode = "";
    }
    if (item.id == id) {
      formData.listBomMat[index].produceStorageId = item.id;
      formData.listBomMat[index].produceStorageCode = item.produceStorageCode;
    }
  });
};
const isOriginalUnified = ref(false);
const addOriginalRow = () => {
  formData.listOriginalMat.push({
    type: "select",
    materialId: "",
    materialCode: "",
    materialName: "",
    quantityUnit: "",
    materialQuantity: 0,
    produceStorageId: "",
    bomId: "",
    bomDetailId: "",
  });
  reBuildSelectMaterialList();
};

const removeOriginalRow = (row) => {
  const indexOf = formData.listOriginalMat.indexOf(row);
  formData.listOriginalMat.splice(indexOf, 1);
  formRef.value.validate();
  reBuildSelectMaterialList();
};

const changeOriginalUnified = () => {
  if (isOriginalUnified.value) {
    formData.listOriginalMat.forEach((item) => {
      item.produceStorageId = formData.originalProduceStorageId;
    });
  }
  formRef.value.validate("originalProduceStorageId");
};
const changeOriginalProduceStorage = () => {
  formData.listOriginalMat.forEach((item,index) => {
    changeRawProduceStorage(index,formData.originalProduceStorageId)
  });

};
const changeRawProduceStorage = (index: number, id: string) => {
  produceStorageList.value.forEach((item: any) => {
    if (!id) {
      formData.listOriginalMat[index].produceStorageId = "";
      formData.listOriginalMat[index].produceStorageCode = "";
    }
    if (item.id == id) {
      formData.listOriginalMat[index].produceStorageId = item.id;
      formData.listOriginalMat[index].produceStorageCode = item.produceStorageCode;
    }
  });
};

const changeOriginalMaterial = ($event, row) => {
  // selectMaterialList.value.push(row.material);
  const find = selectMaterialList.value.find(
    (item) => item.materialId === $event
  );
  if (find) {
    row.materialId = find.materialId;
    row.materialCode = find.materialCode;
    row.materialName = find.materialName;
    row.quantityUnit = find.quantityUnit;
    row.materialQuantity = find.materialQuantity;
    row.material = find;
  } else {
    row.materialId = "";
    row.materialCode = "";
    row.materialName = "";
    row.quantityUnit = "";
    row.materialQuantity = 0;
    row.material = null;
  }
  reBuildSelectMaterialList();
  formRef.value.validate();
};

const produceStorageList = ref([]);

const getProduceStorageList = async () => {
  const { data } = await request({
    url: api.getProduceStorageList,
    method: "post",
    data: {
      workCenterId: rowData.value.workCenterId,
    },
  });
  produceStorageList.value = data;
};

const buildTable = async (data, buildOriginalMat = true) => {
  formData.listBomMat = data;
  selectMaterialList.value = [];
  const bomIds = data.map((item) => item.bomId);
  if (bomIds.length === 0) {
    formData.listOriginalMat = [];
    return;
  }
  await request({
    url: api.getBomDetail,
    method: "post",
    data: {
      ids: bomIds,
    },
  }).then(({ data }) => {
    const map = data
      .map((item) => ({
        type: "search",
        materialId: item.materialId,
        materialCode: item.materialCode,
        materialName: item.materialName,
        quantityUnit: item.quantityUnit,
        materialQuantity: item.matQuantity,
        produceStorageId: "",
        bomId: item.bomId,
        bomDetailId: item.id,
      }))
      .reduce((acc, current) => {
        const existingItem = acc.find(
          (item) => item.materialId === current.materialId
        );
        if (existingItem) {
          existingItem.materialQuantity += current.materialQuantity;
        } else {
          acc.push({ ...current });
        }
        return acc;
      }, []);
    if (buildOriginalMat) {
      formData.listOriginalMat = map;
    }
    allSelectMaterialList.value = JSON.parse(JSON.stringify(map));
  });
};

onMounted(() => {
  // eventBusOn(event.material, async (row) => {
  //   visibleDialog.value = true;
  //   rowData.value = row;
  //   await getProduceStorageList();
  //   if (row.listMat) {
  //     const data = JSON.parse(JSON.stringify(row.listMat)).reduce(
  //       (acc, item) => {
  //         const key = item.materialRole;
  //         if (!acc[key]) {
  //           acc[key] = [];
  //         }
  //         acc[key].push(item);
  //         return acc;
  //       },
  //       {}
  //     );
  //     formData.listBomMat = data[1] ?? [];
  //     formData.listOriginalMat = data[0] ?? [];
  //     await buildTable(formData.listBomMat, false);
  //     reBuildSelectMaterialList();
  //   } else {
  //     formData.listBomMat = [];
  //     formData.listOriginalMat = [];
  //   }
  // });

  // eventBusOn(event.bomTreeSubmit, (data) => {
  //   formData.listBomMat = [];
  //   if (data) {
  //     console.log("data",data)
  //     buildTable(data);
  //   }
  // });
});

const selectMaterialList = ref([]);
const allSelectMaterialList = ref([]);

const reBuildSelectMaterialList = () => {
  const existMaterialIds = formData.listOriginalMat.map(
    (item) => item.materialId
  );
  selectMaterialList.value = allSelectMaterialList.value.filter(
    (item) => !existMaterialIds.includes(item.materialId)
  );
};
const formData = reactive({
  listBomMat: [],
  listOriginalMat: [],
  bomProduceStorageId: "",
  originalProduceStorageId: "",
});

const resetForm = () => {
  formData.listBomMat = [];
  formData.listOriginalMat = [];
  rowData.value = null;
  isBomUnified.value = false;
  isOriginalUnified.value = false;
  formData.bomProduceStorageId = "";
  formData.originalProduceStorageId = "";
  produceStorageList.value = [];
};

const submit = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      formData.listBomMat.forEach((item) => (item.materialRole = 1));
      formData.listOriginalMat.forEach((item) => (item.materialRole = 0));
      rowData.value.listMat = concat(
        formData.listBomMat,
        formData.listOriginalMat
      );
      // eventBusEmit(event.workerSubmit);
      closeDialog();
    }
  });
};

const rules = {
  materialQuantity: [
    {
      required: true,
      message: "请输入基础产出数量",
      trigger: ["blur", "change"],
    },
    {
      validator: validateDecimal,
    },
  ],
  produceStorageId: [
    {
      required: true,
      message: "请选择线边库位",
      trigger: ["blur", "change"],
    },
  ],
  materialId: [
    {
      required: true,
      message: "请选择物料",
      trigger: ["blur", "change"],
    },
  ],
};
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
//BOM
const bomTreeDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
function addBomRow() {
  bomTreeDialog.title = "Bom";
  bomTreeDialog.data = formData.listBomMat;
  bomTreeDialog.visible = true;
}
function changeBomTree(value: boolean, data: any) {
  bomTreeDialog.visible = value;
  if (!value) {
    bomTreeDialog.data = [];
    if (data) {
      formData.listBomMat = [];
      buildTable(data);
    }
  }
}
</script>
